# -*- coding: utf-8 -*-
# created on 2017/01/17

from sympy import sympify, Eq, solve
from mathsolver.functions.sympy_utils import default_symbol
from mathsolver.functions.base.base import new_latex


def jiou_dingyi(jiou):
    """函数奇偶性定义 f(x) = ..."""
    fx = sympify('f(x)')
    return jiou_dingyishi_general(fx, jiou)


def jiou_dingyishi_general(fx, jiou):
    """函数奇偶性定义 f(ax+b) = ..."""
    sym = default_symbol(fx)

    if "奇" in jiou:
        fx_dingyi = -fx.subs(sym, -sym)
    elif "偶" in jiou:
        fx_dingyi = fx.subs(sym, -sym)
    else:
        raise ValueError("input must contain 奇/偶")

    res = Eq(fx, fx_dingyi)
    step = "根据函数奇偶性可知 %s" % new_latex(res)
    return res, step


def dairu_jiou(f_a, jiou_eq):
    """
    把 f(a) 代入 f(x) = -f(x) 或者 f(x) = -f(-x)

    :param f_a sympify 后的 f(a)
    :param jiou_eq 是 Eq 类型
    :return -f(a) 或者 -f(-a)
     """
    a = f_a.args[0]
    symbol = default_symbol(jiou_eq.lhs - jiou_eq.rhs)
    return solve(jiou_eq.subs(symbol, a), f_a)[0]


def dairu_jiou2(f_a, jiou):
    """把 f(a) 或者 -f(a) 代入 f(x) = -f(x) 或者 f(x) = -f(-x)

    :param f_a sympify 后的 f(a)
    :param jiou 值为 '奇'/'偶'
    :return -f(a) 或者 -f(-a)"""
    jiou_eq, step1 = jiou_dingyi(jiou)
    # 如果是 -f(a) 的格式
    if f_a.args[0] == -1:
        sign = -1
        a = (-f_a).args[0]
    else:
        sign = 1
        a = f_a.args[0]

    if "奇" in jiou:
        res = sympify('-f(%s)' % -a) * sign
    else:
        res = sympify('f(%s)' % -a) * sign

    step2 = '代入得 %s = %s' % (f_a, res)
    return res, (step1, step2)


if __name__ == '__main__':
    pass
    # print jiou_dingyishi_general(sympify('f(x+1)'), "奇函数")
    # print jiou_dingyishi_general(sympify('f(x+1)'), "偶函数")
    # print dairu_jiou2(sympify('f(x+1)'), "奇函数")
    # print dairu_jiou2(sympify('-f(x+1)'), "偶函数")
